import nodemailer from "nodemailer";
import { setOtp, verifyOtp } from "./Db/redis";
import { emailType } from "./common";
import CryptoJS from "crypto-js";
import jwt, { JwtPayload } from "jsonwebtoken";
// 生成 6 位数的 OTP
export function generateOtp() {
  return Math.floor(100000 + Math.random() * 900000).toString();
}
//生成15位包括数字大小写标点符号的乱字符
export const generateRandomString = () => {
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  for (let i = 0; i < 15; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    result += characters.charAt(randomIndex);
  }
  return result;
};
//发送邮件
export const sendOTP = (email: string, type: emailType, userIp: string) => {
  return new Promise((resolve, reject) => {
    // 配置 Nodemailer
    const transporter = nodemailer.createTransport({
      host: "smtp.qq.com", // QQ 邮箱 SMTP 服务器
      port: 465, // SMTP 端口号（465 是 SSL 端口）
      secure: true, // true 表示使用 SSL/TLS
      auth: {
        user: "2315167298@qq.com", // 你的 QQ 邮箱
        pass: "cnocxpzvagsseabj", // **不是QQ密码！是你生成的授权码**
      },
    });
    const otp = generateOtp();
    const mailOptions = {
      from: '"StoreIt" <2315167298@qq.com>',
      to: email,
      subject: "您的 OTP 验证码",
      text: `您的验证码是：${otp}，有效期5分钟。请勿泄露给他人。`,
    };
    transporter
      .sendMail(mailOptions)
      ?.then(async (res) => {
        await setOtp(email, otp, type, userIp);
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

//获取文件类型
export const getFileType = (fileName: string) => {
  const extension = fileName.split(".").pop()?.toLowerCase();

  if (!extension) return { type: "other", extension: "" };

  const documentExtensions = [
    "pdf",
    "doc",
    "docx",
    "txt",
    "xls",
    "xlsx",
    "csv",
    "rtf",
    "ods",
    "ppt",
    "odp",
    "md",
    "html",
    "htm",
    "epub",
    "pages",
    "fig",
    "psd",
    "ai",
    "indd",
    "xd",
    "sketch",
    "afdesign",
    "afphoto",
    "afphoto",
  ];
  const imageExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "svg", "webp"];
  const videoExtensions = ["mp4", "avi", "mov", "mkv", "webm"];
  const audioExtensions = ["mp3", "wav", "ogg", "flac"];

  if (documentExtensions.includes(extension))
    return { type: "document", extension };
  if (imageExtensions.includes(extension)) return { type: "image", extension };
  if (videoExtensions.includes(extension)) return { type: "video", extension };
  if (audioExtensions.includes(extension)) return { type: "audio", extension };

  return { type: "other", extension };
};

const key = "yanmengsStore";
// 将对象转为字符串并加密
export function encryptObject(obj: any) {
  try {
    const token = jwt.sign(obj, key, {
      expiresIn: "1d", // 设置JWT有效期为1天
    });
    return token;
  } catch (error) {
    return null;
  }
}

// 解密密文并转为对象
export function decryptObject(ciphertext: string) {
  try {
    if (!ciphertext) return null;
    const decoded = jwt.verify(ciphertext, key) as JwtPayload;
    return decoded; // 返回解码后的JWT内容
  } catch (error) {
    console.error("JWT验证失败:", error);
    return null;
  }
}
